package com.kele.goods.controller;

import com.kele.model.goods.SearchGoods;
import com.kele.common.model.response.PageResult;
import com.kele.common.model.response.Result;
import com.kele.goods.service.GoodsService;
import com.kele.model.goods.Goods;
import com.kele.model.goods.dto.GoodsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("goods")
//@CrossOrigin
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PostMapping("save")
    public Result insert(@RequestBody GoodsDTO goodsDTO){

        Goods goods = goodsDTO.getGoods();
        if(goods.getId()!=null && goods.getId()!=0){
            return goodsService.updateById(goodsDTO);
        }else {
            return goodsService.insert(goodsDTO);
        }
    }

    @GetMapping("selectById/{id}")
    public GoodsDTO selectById(@PathVariable Long id){
        return goodsService.selectById(id);
    }

    @GetMapping("deleteById/{id}")
    public Result deleteById(@PathVariable Long id){
        return goodsService.deleteById(id);
    }

    @PostMapping("findPage/{pageNo}/{pageSize}")
    public PageResult<Goods> findPage(@PathVariable Integer pageNo,
                                      @PathVariable Integer pageSize,
                                      @RequestBody Map serachMap){
        return goodsService.findPage(pageNo,pageSize,serachMap);
    }

    @PostMapping("findUpdatedAfter/{lastSyncTime}")
    public List<SearchGoods> findUpdatedAfter(@PathVariable String lastSyncTime) throws ParseException {
        System.out.println(lastSyncTime);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = dateFormat.parse(lastSyncTime);

        return goodsService.findUpdatedAfter(parse);
    }
}
